<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>学生信息管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../static/layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
<div class="layui-row" id="editStudent" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" id="editForm" action="" style="margin-top:20px">
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="editName" id="editName" required lay-verify="required" autocomplete="off"
                           placeholder="请输入姓名" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">录取号</label>
                <div class="layui-input-block">
                    <input type="text" name="editAdmitId" id="editAdmitId" required lay-verify="required"
                           autocomplete="off"
                           placeholder="请输入录取号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">学号</label>
                <div class="layui-input-block">
                    <input type="text" name="editNum" id="editNum" required lay-verify="required" autocomplete="off"
                           placeholder="请输入学号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="text" name="editPassword" id="editPassword" required lay-verify="required"
                           autocomplete="off"
                           placeholder="请输入密码" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">班级编号</label>
                <div class="layui-input-block">
                    <select name="classNum" lay-verify="required" id="editClassNum">
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="editSex" value="1" title="男">
                    <input type="radio" name="editSex" value="2" title="女">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">宿舍号</label>
                <div class="layui-input-block">
                    <input type="text" name="editDormitory" id="editDormitory" required lay-verify="required"
                           autocomplete="off"
                           placeholder="请输入宿舍号" class="layui-input">
                </div>
            </div>
        </form>
    </div>
</div>

<div class="layui-btn-group actBar" style="float: left;">
    <shiro:hasPermission name="student:del">
        <button class="layui-btn layui-btn-danger layui-btn-sm" data-type="delBatchAll"><i class="layui-icon"></i>批量删除</button>
    </shiro:hasPermission>
    <shiro:hasPermission name="student:add">
        <button class="layui-btn layui-btn-sm" data-type="add"><i class="layui-icon"></i>添加</button>
    </shiro:hasPermission>

</div>

<div class="actBar" style="margin-left: 400px;">
    搜索：
    <div class="layui-inline">
        <input class="layui-input" name="id" id="fuzzySearch" autocomplete="off">
    </div>
    <button class="layui-btn" data-type="fuzzySearch">搜索</button>
</div>
<table class="layui-table" lay-data="{ url:'/student/findAll', page:true, id:'studentList'}" lay-filter="demo">
    <thead>
    <tr>
        <th lay-data="{type: 'checkbox', width: 40, fixed: 'left'}"></th>
        <th lay-data="{field:'id', align:'center', width:60, sort: true, fixed: true}">ID</th>
        <th lay-data="{field:'name', align:'center', width:150}">姓名</th>
        <th lay-data="{field:'admitId', align:'center', width:150, sort: true}">录取号</th>
        <th lay-data="{field:'num', align:'center', width:150, sort: true}">学号</th>
        <th lay-data="{field:'classNum', align:'center', width:150, sort: true}">班级号</th>
        <th lay-data="{field:'sex', align:'center', width:150, sort: true , templet:  function(d){if(d.sex == 1){return '男'}else{return '女'}}}">
            性别
        </th>
        <th lay-data="{field:'dormitory', align:'center', width:150, sort: true}">宿舍号</th>


        <th lay-data="{fixed: 'right', align:'center', width:150, align:'center', toolbar: '#barDemo'}"></th>
    </tr>
    </thead>
</table>

<script type="text/html" id="barDemo">
    <shiro:hasPermission name="student:update">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    </shiro:hasPermission>
    <shiro:hasPermission name="student:del">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </shiro:hasPermission>
</script>


<script src="../static/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script>
    //获取选中ID

    layui.use(['form', 'layer', 'table', 'upload'], function () {
        var table = layui.table
            , form = layui.form, upload = layui.upload, layer = layui.layer;
        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj)
        });
        //监听工具条
        table.on('tool(demo)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作');
            } else if (obj.event === 'del') {
                layer.confirm('确认删除学生吗？', function (index) {
                    $.ajax({
                        url: '/student/del?id=' + data.id,
                        type: "get",
                        dataType: "json",
                        success: function (res) {
                            if (res.code === 200) {
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                layer.close(index);
                                console.log(index);
                                layer.msg("删除成功", {
                                    icon: 1
                                });
                            } else {
                                layer.msg("删除失败", {
                                    icon: 5
                                });
                            }
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改学生信息",
                    content: $("#editStudent")//引用的弹出层的页面层的方式加载修改界面表单
                    , btn: ['确定', '取消'],
                    success: function (layero, index) {
                        $.ajax({
                            url: '/cls/findAll',
                            async: false, //同步执行
                            type: "post",
                            dataType: "json",
                            success: function (res) {
                                if (res.code === 200) {
                                    $("#editClassNum").empty();
                                    for (let i = 0; i < res.data.length; i++) {
                                        // alert(res.data[i].num === data.classNum);
                                        if (res.data[i].num === data.classNum) {
                                            $("#editClassNum").append("<option value='" + res.data[i].id + "' selected>" + res.data[i].num + "</option>");
                                        } else {
                                            $("#editClassNum").append("<option value='" + res.data[i].id + "' >" + res.data[i].num + "</option>");
                                        }

                                    }
                                    $("#editName").val(data.name);
                                    $("#editAdmitId").val(data.admitId);
                                    $("#editNum").val(data.num);
                                    $("input[name='editSex'][value='"+data.sex+"']").attr("checked", true);

                                    $("#editDormitory").val(data.dormitory);
                                    form.render();
                                } else {
                                    layer.msg("获取班级信息失败", {
                                        icon: 5
                                    });
                                }

                            }
                        });

                    },
                    btn1: function (index, layero) {
                        $.ajax({
                            url: '/student/update',
                            type: "post",
                            dataType: "json",
                            data: {
                                id: data.id,
                                name: $("#editName").val(),    //姓名
                                admitId: $("#editAdmitId").val(),    //录取号
                                num: $("#editNum").val(),    //学号
                                password: $("#editPassword").val(),    //密码
                                classNum: $("#editClassNum").val(),    //所属班级
                                sex: $("input[name='editSex").val(),    //性别
                                dormitory: $('#editDormitory').val()    //宿舍号
                            },
                            success: function (res) {
                                if (res.code === 200) {
                                    obj.update({
                                        name: $("#editName").val(),    //姓名
                                        admitId: $("#editAdmitId").val(),    //录取号
                                        num: $("#editNum").val(),    //学号
                                        classNum: $("#editClassNum option:selected").text(),    //所属班级
                                        sex: $("input[name='editSex']:checked").val(),    //性别
                                        dormitory: $('#editDormitory').val()    //宿舍号
                                    });
                                    layer.close(index);
                                    console.log(index);
                                    layer.msg("更新成功", {
                                        icon: 1
                                    });
                                } else {
                                    layer.msg("更新失败", {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    },
                    btn2: function (index, layero) {
                        $("#editStudent").attr("style", "display:none;");
                    }
                    , end: function () {
                        // $("#editName").val('');
                        // $("#editNum").val('');
                        $("#editForm")[0].reset();
                    }
                });
                //动态向表传递赋值可以参看文章进行修改界面的更新前数据的显示，当然也是异步请求的要数据的修改数据的获取
                // setFormValue(obj, data);
            }
        });

        var $ = layui.$, active = {
            add: function () {  //添加学生
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "添加学生信息",
                    content: $("#editStudent")//引用的弹出层的页面层的方式加载修改界面表单
                    , btn: ['确定', '取消'],
                    success: function (layero, index) {
                        $.ajax({
                            url: '/cls/findAll',
                            async: false, //同步执行
                            type: "post",
                            dataType: "json",
                            success: function (res) {
                                if (res.code === 200) {
                                    $("#editClassNum").empty();
                                    for (let i = 0; i < res.data.length; i++) {
                                        $("#editClassNum").append("<option value='" + res.data[i].id + "' >" + res.data[i].num + "</option>");
                                    }
                                    form.render();
                                } else {
                                    layer.msg("获取班级信息失败", {
                                        icon: 5
                                    });
                                }

                            }
                        });

                    },

                    btn1: function (index, layero) {
                        $.ajax({
                            url: '/student/add',
                            type: "post",
                            dataType: "json",
                            data: {
                                name: $("#editName").val(),    //姓名
                                admitId: $("#editAdmitId").val(),    //录取号
                                num: $("#editNum").val(),     //学号
                                password: $("#editPassword").val(),     //密码
                                classNum: $("#editClassNum").val(),     //班级号
                                sex: $("input[name='editSex']:checked").val(),     //性别
                                dormitory: $("#editDormitory").val()     //寝室号
                            },
                            success: function (res) {
                                if (res.code === 200) {
                                    layer.close(index);
                                    console.log(index);
                                    layer.msg("添加成功", {
                                        icon: 1
                                    }, function () {
                                        window.location.reload();
                                    });
                                } else {
                                    layer.msg("添加失败", {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    },
                    btn2: function (index, layero) {
                        $("#editStudent").attr("style", "display:none;");
                    }
                    , end: function () {
                        $("#editName").val('');
                        $("#editNum").val('');
                    }
                });
            },
            //批量删除学生
            delBatchAll: function () {

                var checkStatus = layui.table.checkStatus('studentList'); //studentList 即为基础参数 id 对应的值

                if (checkStatus.data.length > 0) {
                    var idsArray = [];
                    for (var i = 0; i < checkStatus.data.length; i++) {
                        idsArray.push(checkStatus.data[i].id);
                    }
                    var ids = idsArray.toString();
                    console.log(ids);
                    layer.confirm('确认删除这些学生吗？', function (index) {
                        $.ajax({
                            url: '/student/delBatchAll',
                            type: "post",
                            dataType: "json",
                            data: {
                                ids: ids
                            },
                            success: function (res) {
                                if (res.code === 200) {
                                    layer.close(index);
                                    layer.msg("删除成功", {
                                        icon: 1
                                    }, function () {
                                        window.location.reload();
                                    });
                                } else {
                                    layer.msg("删除失败", {
                                        icon: 5
                                    });
                                }
                            }
                        });
                    });
                } else {
                    layui.layer.alert("请至少选择一行");
                }
            },
            fuzzySearch: function () {
                var fuzzySearch = $('#fuzzySearch');

                //执行重载
                table.reload('studentList', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        key: fuzzySearch.val()
                    }
                });
            }
        };

        $('.actBar .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>

</body>
</html>